﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SharePoint;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using NCS.IConnect.ApplicationContexts;
using JM.JCY.Common;
using JM.JCY.BusinessEntity.DSJCYD94;

namespace JM.JCY.MasterPage
{
    public partial class JCYMasterPage : System.Web.UI.MasterPage
    {

        #region constants

        public int _userId
        {
            set { ViewState["_userId"] = value; }
            get { return (int)ViewState["_userId"]; }
        }
        public string _userName
        {
            set { ViewState["_userName"] = value; }
            get { return (string)ViewState["_userName"]; }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb CurrentWeb = SPContext.Current.Web;
            _userName = CurrentWeb.CurrentUser.LoginName.ToString().Substring(CurrentWeb.CurrentUser.LoginName.LastIndexOf("|") + 1);

            // load department and committee
            using (UserManagementProxy userProxy = new UserManagementProxy())
            {
                // get user Id
                DataSetUserManagement.T_UserInfoDataTable userDT = userProxy.GetUser(0, _userName);
                if (userDT.Rows.Count > 0)
                    _userId = userDT[0].ID;
                else
                    _userId = 0;

                // *** load all department ***
                //DataSetUserManagement.T_DepartmentDataTable dtDepartment = userProxy.GetAllDepartment();
                //this.DataListGroup.DataSource = dtDepartment;
                //this.DataListGroup.DataBind();

                // *** load user related department ***
                DepartmentTitleDataSet.T_User_Dept_DataDataTable dtDepartment = userProxy.GetUserDept(_userId);
                this.DataListGroup.DataSource = dtDepartment;
                this.DataListGroup.DataBind();

                FrameworkDataset.T_MyCommitteeDataTable dtMyCommittee = userProxy.GetMyCommittee(_userName);
                this.DataListMyComitee.DataSource = dtMyCommittee;
                this.DataListMyComitee.DataBind();

                //// load group info
                //if (Request.Params["DeptId"] != null && Request.QueryString["DeptId"].Equals(string.Empty) == false)
                //{
                //    int deptId = Int32.Parse(Request.QueryString["DeptId"]);
                //    DataSetUserManagement.T_DepartmentDataTable deptDT = userProxy.GetDeptById(deptId, string.Empty);
                //    this.lblGroupInfo.Text = deptDT[0].DeptName;
                //}


                //if (Request.Params["CommitteeId"] != null && Request.QueryString["CommitteeId"].Equals(string.Empty) == false)
                //{
                //    int CommitteeId = Int32.Parse(Request.QueryString["CommitteeId"]);
                //    CommitteeDataSet.T_CommitteeDataTable CommitteeDT = userProxy.GetCommitteeById(CommitteeId);
                //    this.lblGroupInfo.Text = CommitteeDT[0].CommitteeName;

                //}

                //// hide group if on home page
                //if (CurrentWeb.Title == string.Empty)
                //{
                //    this.lblGroupInfo.Visible = false;
                //}

            }

            // load app Data
            using (ApplicationProxy appProxy = new ApplicationProxy())
            {
                ApplicationDataSet.T_ApplicationDataTable appDT = appProxy.GetApplicationByType("MyApp", "Y");
                this.DataListApps.DataSource = appDT;
                this.DataListApps.DataBind();
            }

            // load app Event
            using (EventProxy appProxy = new EventProxy())
            {
                EventDataset.T_EventDataTable dt = appProxy.GetMyEvent(SPContext.Current.Web.CurrentUser.Name,"未完成","top");
                this.DataListEvent.DataSource = dt;
                this.DataListEvent.DataBind();
            }


            using (NotificationProxy notiProxy = new NotificationProxy())
            {
                NotificationDataSet.NotificationTableDataTable notiData = notiProxy.GetTopXNotifications(_userId);
                DataListNotify.DataSource = notiData;
                DataListNotify.DataBind();

            

            }

            // load other parts
            this.lbWelcome.Text = _userName;

            SetApplicationContexts(_userName, _userId);

            // load home page
            if (CurrentWeb.Title == JCY.Common.JCYConstant.SiteName.MySite)
            {
                this.lblGroupInfo.Visible = false;

                LoadSiteLogoStatus(JCY.Common.JCYConstant.SiteImageUrl.Site_S, JCY.Common.JCYConstant.SiteImageUrl.WorkGroup_U, JCY.Common.JCYConstant.SiteImageUrl.Committee_U, "true", "false", "false");
            }
            // load my dept
            else if (CurrentWeb.Title == JCY.Common.JCYConstant.SiteName.MyDept)
            {
                LoadSiteLogoStatus(JCY.Common.JCYConstant.SiteImageUrl.Site_U, JCY.Common.JCYConstant.SiteImageUrl.WorkGroup_S, JCY.Common.JCYConstant.SiteImageUrl.Committee_U, "false", "true", "false");
            }
            // load my committee
            else if (CurrentWeb.Title == JCY.Common.JCYConstant.SiteName.MyCommittee)
            {
                LoadSiteLogoStatus(JCY.Common.JCYConstant.SiteImageUrl.Site_U, JCY.Common.JCYConstant.SiteImageUrl.WorkGroup_U, JCY.Common.JCYConstant.SiteImageUrl.Committee_S, "false", "false", "true");
            }
            // load others
            else
            {
                LoadSiteLogoStatus(JCY.Common.JCYConstant.SiteImageUrl.Site_U, JCY.Common.JCYConstant.SiteImageUrl.WorkGroup_U, JCY.Common.JCYConstant.SiteImageUrl.Committee_U, "false", "false", "false");
            }

        }

        #region Set Context Id

        private void SetApplicationContexts(string userName, int userId)
        {
            ApplicationContext.Current.UserName = userName;
            ApplicationContext.Current.SetKeyValue("userId", userId);
        }

        protected void IMGBtnMySite_Click(object sender, ImageClickEventArgs e)
        {
            ApplicationContext.Current.SetKeyValue("appType", JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName);
            if (SPContext.Current.Web.Title != JCYConstant.SiteName.MySite)
                Response.Redirect(SPContext.Current.Web.ParentWeb.Url);
            else
                Response.Redirect(SPContext.Current.Web.Url);
        }

        protected void DataListGroup_OnItemCommand(object sender, DataListCommandEventArgs e)
        {
            if (e.CommandName == "LinkContent")
            {
                ApplicationContext.Current.SetKeyValue("appType", JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName);
                ApplicationContext.Current.SetKeyValue("AppId", e.CommandArgument.ToString());
                Response.Redirect("/MyDept/default.aspx?DeptId=" + e.CommandArgument.ToString());
            }
        }

        protected void DataListComitee_OnItemCommand(object sender, DataListCommandEventArgs e)
        {
            if (e.CommandName == "LinkContent")
            {
                ApplicationContext.Current.SetKeyValue("appType", JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName);
                ApplicationContext.Current.SetKeyValue("AppId", e.CommandArgument.ToString());
                Response.Redirect("/MyCommittee/default.aspx?CommitteeId=" + e.CommandArgument.ToString());
            }
        }

        #endregion

        #region Methods

        private int GetCaseWarningByCurrentAccount()
        {
            using (DSJCYD94Proxy proxy = new DSJCYD94Proxy())
            {
                return proxy.GetCaseWarningCountByCBR(SPContext.Current.Web.CurrentUser.Name);
            }
        }

        private DataTable GetNewDataTable(DataTable dt, string condition)
        {
            DataTable newDT = new DataTable();
            newDT = dt.Clone();
            DataRow[] dr = dt.Select(condition);
            for (int i = 0; i <= dr.Length - 1; i++)
            {
                newDT.ImportRow((DataRow)dr[i]);
            }
            return newDT;
        }

        private void LoadSiteLogoStatus(string mySiteUrl, string myWorkGroupUrl, string myCommiteeUrl, string siteStatus, string workGroupStatus, string committeeStatus)
        {
            this.IMGBtnMySite.ImageUrl = mySiteUrl;
            this.IMGMyGroup.ImageUrl = myWorkGroupUrl;
            this.IMGMyComittee.ImageUrl = myCommiteeUrl;
            ((HiddenField)this.Page.Master.FindControl("HiddenMySiteFlag")).Value = siteStatus;
            ((HiddenField)this.Page.Master.FindControl("HiddenMyWorkGroupFlag")).Value = workGroupStatus;
            ((HiddenField)this.Page.Master.FindControl("HiddenMyCommitteeFlag")).Value = committeeStatus;
        }

        #endregion

        #region Datalist Events

        protected void DataListGroup_OnItemDataBound(object sender, DataListItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton lkb = (LinkButton)e.Item.FindControl("LinkMyGroup");
                Label lbl = (Label)e.Item.FindControl("lblMyGroup");

            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {
                LinkButton lkbViewAll = (LinkButton)e.Item.FindControl("LinkViewAll");
                string redirectUrl = "/MyDept/DepartmentPages/ViewAllDepartment.aspx";
                lkbViewAll.Attributes.Add("href", redirectUrl);
            }

        }

        protected void DataListComitee_OnItemDataBound(object sender, DataListItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                //LinkButton lkb = (LinkButton)e.Item.FindControl("LinkMyComitee");
                //Label lbl = (Label)e.Item.FindControl("lbMyComitee");

            }
             else if (e.Item.ItemType == ListItemType.Footer)
            {
                LinkButton lkbViewAll = (LinkButton)e.Item.FindControl("LinkCreateCommittee");
                string redirectUrl = "/MyCommittee/CommitteePages/CreateCommittee.aspx";
                lkbViewAll.Attributes.Add("href", redirectUrl);
            }
        }

        protected void DataListNotification_OnItemDataBound(object sender, DataListItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton lkb = (LinkButton)e.Item.FindControl("LinkNotificationItem");
                //string redirectUrl = drv["RedirectUrl"].ToString();
                string redirectUrl = SPContext.Current.Site.ServerRelativeUrl + "CaseManagementPages/CaseWarningforNotification.aspx";
                lkb.Attributes.Add("href", redirectUrl);
            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {

                //LinkButton LinkViewAllNotification = (LinkButton)e.Item.FindControl("LinkViewAllNotification");
                //int caseCount = GetCaseWarningByCurrentAccount();

                //if (caseCount > 0)
                //{
                //    LinkViewAllNotification.Text = "您有【" + caseCount + "】件案件被预警,查看详细！";
                //    string redirectUrl = SPContext.Current.Site.ServerRelativeUrl + "CaseManagementPages/CaseWarningforNotification.aspx";
                //    LinkViewAllNotification.Attributes.Add("href", redirectUrl);
                //}
                //else
                //    LinkViewAllNotification.Text = "暂时还没有提醒信息！";

            }
        }

        protected void DataListApps_OnItemDataBound(object sender, DataListItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string applicationName = drv["ApplicationName"].ToString();
                LinkButton lkb = (LinkButton)e.Item.FindControl("LinkApps");
                lkb.Text = "<img  height='32' width='32' src=" + drv["ApplicationImgUrlSmall"].ToString() + ">" + "&nbsp;&nbsp;" + drv["ApplicationName"].ToString();
                string redirectUrl = SPContext.Current.Site.ServerRelativeUrl + drv["HomeUrl"].ToString();
                lkb.Attributes.Add("href", redirectUrl + "?StaffId=" + _userId);
            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {
                LinkButton lkbViewAll = (LinkButton)e.Item.FindControl("LinkViewAll");
                string redirectUrl = SPContext.Current.Site.ServerRelativeUrl + "pages/ViewAllApplications.aspx";
                lkbViewAll.Attributes.Add("href", redirectUrl);
            }

        }


        protected void DataListEvent_OnItemDataBound(object sender, DataListItemEventArgs e)
        {

            DataRowView drv = (DataRowView)e.Item.DataItem;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string eventSubject = drv["Subject"].ToString();
                LinkButton lkb = (LinkButton)e.Item.FindControl("LinkEvent");
                lkb.Text = eventSubject;
                string redirectUrl = SPContext.Current.Site.ServerRelativeUrl + "EventPages/EditEvent.aspx";
                lkb.Attributes.Add("href", redirectUrl + "?EventId=" + drv["ID"]);

            }
            else if (e.Item.ItemType == ListItemType.Footer)
            {
                LinkButton lkbViewAll = (LinkButton)e.Item.FindControl("LinkViewAll");
                string redirectUrl = SPContext.Current.Site.ServerRelativeUrl + "EventPages/SearchEventSender.aspx";
                lkbViewAll.Attributes.Add("href", redirectUrl);
            }

        }
        #endregion

        #region Others

        protected void ImgBtnLogo_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect(SPContext.Current.Web.Url);
        }

        #endregion
    }
}